package org.balabala.os.client;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import io.minio.http.Method;
import org.balabala.os.conf.ObjectStorageConf;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class MinIOClient {
    private io.minio.MinioClient client;

    private String bucketName;

    private MinIOClient(){}

    public static MinIOClient build(ObjectStorageConf conf) {
        MinIOClient minioClient = new MinIOClient();

        minioClient.client = io.minio.MinioClient.builder().
                endpoint(conf.getEndpoint()).
                credentials(conf.getAccessKey(), conf.getSecretKey()).
                build();
        minioClient.bucketName = conf.bucketName;

        return minioClient;
    }

    public void putObject(String objectKey, String contentType,InputStream inputStream) throws IOException, ServerException, InsufficientDataException, InternalException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, XmlParserException, ErrorResponseException {
        ObjectWriteResponse owr = this.client.putObject(PutObjectArgs.builder().
                bucket(this.bucketName).
                object(objectKey).
                contentType(contentType).
                stream(inputStream, inputStream.available(), -1).
                build()
        );
    }

    public String getObjectUrl(String objectKey, int expiryMinutes) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        return this.client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder().
                bucket(this.bucketName).
                object(objectKey).
                method(Method.GET).
                expiry(expiryMinutes).
                build()
        );
    }
}
